#include "userpage.h"
#include "ui_userpage.h"
#include<QDebug>
#include<QMessageBox>
#include <QDialog>
#include <QFormLayout>
#include <QLineEdit>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QSqlQuery>
#include <QFile>
#include<QFileDialog>
UserPage::UserPage(QSqlDatabase &d,QString InId) :
//    QWidget(parent),
    db(d),
    myId(InId),
    ui(new Ui::UserPage)
{
    ui->setupUi(this);
    d_model=new QSqlTableModel(this,db);
    d_model->setTable("login");
    initMe();
//    ui->tableView->setEditTriggers(QTableView::DoubleClicked);//设置双击后可以编辑
}

UserPage::~UserPage()
{
    delete ui;
}
void UserPage::initMe(){
    QString search = myId;

    QSqlQuery query(db);

    // 根据条件查询用户
    query.prepare("SELECT * FROM student WHERE S_Id = :search");
    query.bindValue(":search", search);
    if (query.exec()) {
        if (query.next()) {
            ui->S_Id->setText(query.value(0).toString());
            ui->S_Name->setText(query.value(1).toString());
            ui->S_Class->setText(query.value(2).toString());
            ui->S_Age->setText(query.value(3).toString());
            ui->S_Sex->setText(query.value(4).toString());
            ui->S_Pno->setText(query.value(5).toString());
            ui->zhHao->setText(myId);
        } else {
            qDebug() << "没有找到匹配的记录";
        }
    } else {
        qDebug() << "查询错误:" << query.lastError();
        QMessageBox::critical(this, tr("错误"), tr("查询失败：") + query.lastError().text());
    }
    query.prepare("SELECT image FROM login WHERE S_Id = :search");
    query.bindValue(":search", search);

    QPixmap pixmap;
    if (query.exec()) {
        if (query.next()) {
            QString imagePath = query.value(0).toString();
            qDebug()<<imagePath;
            pixmap.load(imagePath); // 加载图片
            if (pixmap.isNull()) {
                qDebug() << "图片加载失败";
//                imagePath=":/pic/user.png";
                imagePath="C:/Users/20340/Desktop/PIC/2.jpg";
                pixmap.load(imagePath); // 加载图片
                pixmap = pixmap.scaled(ui->picLab->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
                ui->picLab->setPixmap(pixmap);
            } else {
                pixmap = pixmap.scaled(ui->picLab->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
                ui->picLab->setPixmap(pixmap);
            }
        } else {
            qDebug() << "没有找到匹配的记录";
        }
    } else {
        qDebug() << "查询错误:" << query.lastError();
        QMessageBox::critical(this, tr("错误"), tr("查询失败：") + query.lastError().text());
    }
}

void UserPage::on_rueBut_clicked()
{
//    d_model->submitAll();
//    getAllUsers();
    initMe();
}

/*void UserPage::on_pushButton_7_clicked()
{
    // 创建一个对话框来输入用户信息
    QDialog addUserDialog(this);
    addUserDialog.setWindowTitle(tr("修改"));

    // 创建输入字段
    QFormLayout *formLayout = new QFormLayout;
    QLineEdit *Old_pass= new QLineEdit;
    Old_pass->setEchoMode(QLineEdit::Password); // 密码输入框
    // 添加输入字段到布局
    formLayout->addRow(tr("请输入旧密码:"), Old_pass);

    // 创建按钮和布局
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, &QDialogButtonBox::accepted, &addUserDialog, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, &addUserDialog, &QDialog::reject);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addLayout(formLayout);
    layout->addWidget(buttonBox);
    addUserDialog.setLayout(layout);

    // 显示对话框并检查结果
    if (addUserDialog.exec() == QDialog::Accepted) {
        QString oPassIn = Old_pass->text();

        // 查找
        QSqlQuery query(db);
        QString sql=QString("select S_Passwd from `login` where S_Id='%1';").arg(myId);
        if (!query.exec(sql)) {
            QMessageBox::critical(this, tr("错误"), tr("错误") + query.lastError().text());
        }
        if (query.next()) {
             QString oldpass = query.value(0).toString();
             if(oldpass==oPassIn){
                 // 创建一个对话框来输入新密码
                 QDialog addUserDialog(this);
                 addUserDialog.setWindowTitle(tr("修改密码"));

                 // 创建输入字段
                 QFormLayout *formLayout = new QFormLayout;
                 QLineEdit *passwordEdit = new QLineEdit;
                 QLineEdit *passwordEdit_1 = new QLineEdit;
                 passwordEdit->setEchoMode(QLineEdit::Password);
                 passwordEdit_1->setEchoMode(QLineEdit::Password); // 密码输入框


                 // 添加输入字段到布局

                 formLayout->addRow(tr("密码:"), passwordEdit);
                 formLayout->addRow(tr("确认密码:"), passwordEdit_1);


                 // 创建按钮和布局
                 QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
                 connect(buttonBox, &QDialogButtonBox::accepted, &addUserDialog, &QDialog::accept);
                 connect(buttonBox, &QDialogButtonBox::rejected, &addUserDialog, &QDialog::reject);

                 QVBoxLayout *layout = new QVBoxLayout;
                 layout->addLayout(formLayout);
                 layout->addWidget(buttonBox);
                 addUserDialog.setLayout(layout);

                 // 显示对话框并检查结果
                 if (addUserDialog.exec() == QDialog::Accepted) {
                     QString password = passwordEdit->text();
                     QString password_1 = passwordEdit_1->text();
                     if(password!=password_1)
                         QMessageBox::information(this, tr("错误"), tr("两次输入密码不相同"));

                     // 修改密码
                     else {
                         QSqlQuery query(db);
                         QString sql=QString("修改语句('%1');").arg(password);
                         if (query.exec(sql)) {
                             QMessageBox::information(this, tr("成功"), tr("修改成功"));
                         } else {
                             QMessageBox::critical(this, tr("错误"), tr("修改失败") + query.lastError().text());
                         }
                     }

                 }
             }
        }
    }
}
*/
void UserPage::on_pushButton_7_clicked()
{
    // 直接调用输入旧密码的函数
    oldPasswordInput();
}

void UserPage::oldPasswordInput()
{
    // 创建一个对话框来输入旧密码
    QDialog *oldPasswordDialog = new QDialog(this);
    oldPasswordDialog->setWindowTitle(tr("验证旧密码"));

    // 创建输入字段
    QFormLayout *formLayout = new QFormLayout;
    QLineEdit *oldPassEdit = new QLineEdit;
    oldPassEdit->setEchoMode(QLineEdit::Password); // 密码输入框
    // 添加输入字段到布局
    formLayout->addRow(tr("请输入旧密码:"), oldPassEdit);

    // 创建按钮和布局
    QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(buttonBox, &QDialogButtonBox::accepted, [this, oldPassEdit, oldPasswordDialog]() {
        QString oldPass = oldPassEdit->text();
        // 查找
        QSqlQuery query(db);
        QString sql = QString("SELECT S_Passwd FROM `login` WHERE S_Id = '%1';").arg(myId);
        if (!query.exec(sql)) {
            QMessageBox::critical(this, tr("错误"), tr("错误") + query.lastError().text());
            oldPasswordDialog->accept();
        } else {
            if (query.next()) {
                QString storedPass = query.value(0).toString();
                if (storedPass == oldPass) {
                    oldPasswordDialog->accept();
                    this->changePassword();
                } else {
                    QMessageBox::information(this, tr("错误"), tr("旧密码不正确"));
                }
            }
        }
    });
    connect(buttonBox, &QDialogButtonBox::rejected, oldPasswordDialog, &QDialog::reject);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addLayout(formLayout);
    layout->addWidget(buttonBox);
    oldPasswordDialog->setLayout(layout);

    // 显示对话框
    if(oldPasswordDialog->exec() == QDialog::Accepted) {
        // 用户点击了OK，继续执行changePassword
    } /*else {
        // 用户点击了Cancel或关闭了对话框，可以在这里重新调用oldPasswordInput来重新输入
        QTimer::singleShot(0, this, &UserPage::oldPasswordInput); // 使用定时器来重新调用函数，避免递归调用的问题
    }*/
}

void UserPage::changePassword()
{
    // 创建一个对话框来输入新密码
    QDialog *newPasswordDialog = new QDialog(this);
    newPasswordDialog->setWindowTitle(tr("修改密码"));

    // 创建输入字段
    QFormLayout *newFormLayout = new QFormLayout;
    QLineEdit *passwordEdit = new QLineEdit;
    QLineEdit *passwordEdit_1 = new QLineEdit;
    passwordEdit->setEchoMode(QLineEdit::Password);
    passwordEdit_1->setEchoMode(QLineEdit::Password); // 密码输入框

    // 添加输入字段到布局
    newFormLayout->addRow(tr("密码:"), passwordEdit);
    newFormLayout->addRow(tr("确认密码:"), passwordEdit_1);

    // 创建按钮和布局
    QDialogButtonBox *newButtonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(newButtonBox, &QDialogButtonBox::accepted, [this, passwordEdit, passwordEdit_1, newPasswordDialog]() {
        QString password = passwordEdit->text();
        QString password_1 = passwordEdit_1->text();
        if (password != password_1) {
            QMessageBox::information(this, tr("错误"), tr("两次输入密码不相同"));
            passwordEdit->clear();
            passwordEdit_1->clear();
            return;
        }
        // 修改密码
        QSqlQuery updateQuery(db);
        QString updateSql = QString("UPDATE `login` SET S_Passwd = '%1' WHERE S_Id = '%2';").arg(password).arg(myId);
        if (updateQuery.exec(updateSql)) {
            QMessageBox::information(this, tr("成功"), tr("修改成功"));
            newPasswordDialog->accept();
        } else {
            QMessageBox::critical(this, tr("错误"), tr("修改失败") + updateQuery.lastError().text());
        }
    });
    connect(newButtonBox, &QDialogButtonBox::rejected, newPasswordDialog, &QDialog::reject);

    QVBoxLayout *newLayout = new QVBoxLayout;
    newLayout->addLayout(newFormLayout);
    newLayout->addWidget(newButtonBox);
    newPasswordDialog->setLayout(newLayout);

    // 显示对话框
    newPasswordDialog->exec();
}

void UserPage::on_chImageBut_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("选择图片"), "", tr("Image files (*.png *.jpg *.jpeg)"));

    if (!fileName.isEmpty()) {
        // 保存图片到服务器或本地的路径
        QString savePath = "C:/Users/20340/Desktop/PIC/" + QFileInfo(fileName).fileName();

        // 如果目标文件已存在，则删除它
        QFile destFile(savePath);
        if (destFile.exists() && !destFile.remove()) {
            qDebug() << "无法删除已存在的文件：" << savePath;
            return;
        }

        // 复制文件，如果目标文件已存在，则会被替换
        if (QFile::copy(fileName, savePath)) {
            // 图片保存成功，现在将路径存储到数据库
            QString imagePath = savePath; // 根据实际情况调整路径
            QSqlQuery query;
            query.prepare("UPDATE login SET image = :ImagePath WHERE S_Id = :Id"); // 假设您是根据id来更新记录
            query.bindValue(":ImagePath", imagePath); // imagePath是您要更新的图片路径
            query.bindValue(":Id", myId); // myId是您要更新的记录的id
            if (query.exec()) {
                qDebug() << "图片路径存储成功";
            } else {
                qDebug() << "存储失败:" << query.lastError();
            }
        } else {
            qDebug() << "图片保存失败";
        }
    }
}
